Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

Using the JMS API in a J2EE Application

This section describes the ways in which using the JMS API in a J2EE application differs from using it in a standalone client application:

A general rule new at J2EE version 1.4 applies to all J2EE components that use EJB or Web containers:

Any component within an EJB or Web container must have no more than one JMS session per JMS connection.

This rule does not apply to application clients.

Using Session and Entity Beans to Produce and to Synchronously Receive Messages

A J2EE application that produces messages or synchronously receives them may use either a session bean or an entity bean to perform these operations. The example in A J2EE Application that Uses the JMS API with a Session Bean uses a stateless session bean to publish messages to a topic.

Because a blocking synchronous receive ties up server resources, it is not a good programming practice to use such a receive call in an enterprise bean. Instead, use a timed synchronous receive, or use a message-driven bean to receive messages asynchronously. For details about blocking and timed synchronous receives, see Writing the Client Programs.

Using the JMS API in a J2EE application is in many ways similar to using it in a standalone client. The main differences are in administered objects, resource management, and transactions.

Administered Objects

The J2EE Platform Specification recommends that you use java:comp/env/jms as the environment subcontext for JNDI lookups of connection factories and destinations. With the J2EE Application Server, you use the J2EE Deploytool, commonly known as the deploytool, to specify JNDI names that correspond to those in your source code.

Instead of looking up a JMS API connection factory or destination each time it is used in a method, it is recommended that you look up these instances once in the enterprise bean's ejbCreate method and cache them for the lifetime of the enterprise bean.

Resource Management

JMS API resources are a JMS API connection and a JMS API session. In general, it is important to release JMS resources when they are no longer being used. Here are some useful practices to follow.

Transactions

Instead of using local transactions, you use the deploytool to specify container-managed transactions for bean methods that perform sends or receives, allowing the EJB container to handle transaction demarcation.

You can use bean-managed transactions and the javax.transaction.UserTransaction interface's transaction demarcation methods, but you should do so only if your application has special requirements and you are an expert in using transactions. Usually, container-managed transactions produce the most efficient and correct behavior. This tutorial does not provide any examples of bean-managed transactions.

Using Message-Driven Beans

As we noted in How Does the JMS API Work with the J2EE Platform?, the J2EE platform supports a special kind of enterprise bean, the message-driven bean, which allows J2EE applications to process JMS messages asynchronously. Session beans and entity beans allow you to send messages and to receive them synchronously but not asynchronously.

A message-driven bean is a message listener that can reliably consume messages from a queue or a durable subscription. The messages may be sent by any J2EE component--from an application client, another enterprise bean, or a Web component--or from an application or a system that does not use J2EE technology.

Like a message listener in a standalone JMS client, a message-driven bean contains an onMessage method that is called automatically when a message arrives. Like a message listener, a message-driven bean class may implement helper methods invoked by the onMessage method to aid in message processing.

A message-driven bean differs from a standalone client's message listener in the following ways, however:

The EJB container automatically performs several setup tasks that a standalone client has to do:

If JMS is integrated with the application server using a resource adapter, the JMS resource adapter handles these tasks for the EJB container. It creates a connection factory for the message-driven bean to use. You use an activation configuration specification to specify properties for the connection factory, such as a durable subscription, a message selector, or an acknowledgment mode. See Specifying Activation Configuration Properties for Message-Driven Beans for details. The examples in Chapter 21 show how the JMS resource adapter works in the J2EE 1.4 Application Server.

Your message-driven bean class must implement the following, in addition to the onMessage method:

The main difference between a message-driven bean and other enterprise beans is that a message-driven bean has no home or remote interface. Instead, it has only a bean class.

A message-driven bean is similar in some ways to a stateless session bean: its instances are relatively short-lived and retain no state for a specific client. The instance variables of the message-driven bean instance can contain some state across the handling of client messages: for example, a JMS API connection, an open database connection, or an object reference to an enterprise bean object.

Like a stateless session bean, a message-driven bean can have many interchangeable instances running at the same time. The container can pool these instances to allow streams of messages to be processed concurrently. Concurrency can affect the order in which messages are delivered, so you should write your application to handle messages that arrive out of sequence. See A J2EE Application that Uses the JMS API with an Entity Bean for an example.

To create a new instance of a message-driven bean, the container instantiates the bean and then

Figure 20-10 shows the life cycle of a message-driven bean.

Life Cycle of a Message-Driven Bean

Figure 20-10 Life Cycle of a Message-Driven Bean

Managing Distributed Transactions

JMS client applications use JMS API local transactions, described in Using JMS API Local Transactions, which allow the grouping of sends and receives within a specific JMS session. J2EE applications commonly use distributed transactions in order to ensure the integrity of accesses to external resources. For example, distributed transactions allow multiple applications to perform atomic updates on the same database, and they allow a single application to perform atomic updates on multiple databases.

In a J2EE application that uses the JMS API, you can use transactions to combine message sends or receives with database updates and other resource manager operations. You can access resources from multiple application components within a single transaction. For example, a servlet may start a transaction, access multiple databases, invoke an enterprise bean that sends a JMS message, invoke another enterprise bean that modifies an EIS system using the Connector architecture, and finally commit the transaction. Your application cannot, however, both send a JMS message and receive a reply to it within the same transaction; the restriction described in Using JMS API Local Transactions still applies.

Distributed transactions can be either of two kinds:

You can use either container-managed transactions or bean-managed transactions with message-driven beans.

To ensure that all messages are received and handled within the context of a transaction, use container-managed transactions and specify the Required transaction attribute for the onMessage method. This means that if there is no transaction in progress, a new transaction will be started before the method is called and will be committed when the method returns.

When you use container-managed transactions, you can call the following MessageDrivenContext methods:

If you use bean-managed transactions, the delivery of a message to the onMessage method takes place outside of the distributed transaction context. The transaction begins when you call the UserTransaction.begin method within the onMessage method and ends when you call UserTransaction.commit. Any call to the Connection.createSession method must take place within the transaction. If you call UserTransaction.rollback, the message is not redelivered, whereas calling setRollbackOnly for container-managed transactions does cause a message to be redelivered.

Neither the JMS API Specification nor the Enterprise JavaBeans Specification (available from http://java.sun.com/products/ejb/) specifies how to handle calls to JMS API methods outside transaction boundaries. The Enterprise JavaBeans Specification does state that the EJB container is responsible for acknowledging a message that is successfully processed by the onMessage method of a message-driven bean that uses bean-managed transactions. Using bean-managed transactions allows you to process the message by using more than one transaction or to have some parts of the message processing take place outside a transaction context. In most cases, however, container-managed transactions provide greater reliability and are therefore preferable.

When you create a session in an enterprise bean, the container ignores the arguments you specify, because it manages all transactional properties for enterprise beans. It is still a good idea to specify arguments of true and 0 to the createSession method to make this situation clear:

session = connection.createSession(true, 0); 

When you use container-managed transactions, you usually specify the Required transaction attribute for your enterprise bean's business methods.

You do not specify a message acknowledgment mode when you create a message-driven bean that uses container-managed transactions. The container acknowledges the message automatically when it commits the transaction.

If a message-driven bean uses bean-managed transactions, the message receipt cannot be part of the bean-managed transaction, so the container acknowledges the message outside of the transaction. When you package a message-driven bean using the deploytool, you use activation configuration properties to specify the acknowledgment mode. See Table 20-7 on page 756 for details.

If the onMessage method throws a RuntimeException, the container does not acknowledge processing the message. In that case, the JMS provider will redeliver the unacknowledged message in the future.

Using the JMS API with Application Clients and Web Components

An application client can use the JMS API in much the same way a standalone client program does. It can produce messages, and it can consume messages by using either synchronous receives or message listeners. See A Simple J2EE Application that Uses the JMS API for an example of an application client that produces messages; see A J2EE Application that Uses the JMS API with an Entity Bean and An Application Example that Deploys a Message-Driven Bean on Two J2EE Servers for examples of using application clients to produce and to consume messages.

The J2EE Platform Specification does not impose strict constraints on how Web components should use the JMS API. In the J2EE 1.4 Application Server, a Web component--one that uses either the Java Servlet API or JavaServerPages (JSP) technology--may send messages and consume them synchronously but may not consume them asynchronously.

Because a blocking synchronous receive ties up server resources, it is not a good programming practice to use such a receive call in a Web component. Instead, use a timed synchronous receive. For details about blocking and timed synchronous receives, see Writing the Client Programs.

Specifying Deployment Descriptors

When you package a J2EE application, you provide deployment descriptors for the application and its modules. This section describes the deployment descriptor elements specific to an application that uses the JMS API and message-driven beans. At release 1.4 of the J2EE platform, message-driven beans can be configured to consume messages from other messaging sources in addition to JMS providers.

At release 1.4 of the J2EE platform, application servers must be able to support both DTDs and XML schemas. The order in which you specify elements in deployment descriptors is not significant when you use DTDs, but it is significant when you use XML schemas. Therefore, it is a good idea to use the J2EE deploytool provided with the J2EE Application Server to create the deployment descriptors for you.

This section covers the following topics:

Deployment Descriptor Elements for Connection Factories and Destinations

Modules that send messages or receive messages synchronously use the elements listed in Table 20-4. These elements describe the JMS resources referenced in module source code: connection factories and destinations. The XML Schema files used by the J2EE Application Server are in the directory <J2EE_HOME>/lib/schemas/.You use these elements in deployment descriptors for application clients, enterprise beans, and Web components.

Table 20-4 Deployment Descriptor Elements for Connection Factories and Destinations
Element Name
Description
<resource-ref>
Contains a declaration of the enterprise bean's reference to an external resource, such as a JMS API connection factory. Contains the elements <res-ref-name>, <res-type>, and <res-auth>.
<res-ref-name>
Specifies the coded name of a resource manager connection factory reference, such as jms/MyConnectionFactory.
<res-type>
Specifies the type of the data source. The type is specified by the Java interface expected to be implemented by the connection factory. For JMS connection factories, the allowed interfaces are javax.jms.ConnectionFactory, javax.jms.QueueConnectionFactory, and javax.jms.TopicConnectionFactory.
<res-auth>
Specifies whether the enterprise bean code signs on programmatically to the resource manager (Application) or whether the Container will sign on to the resource manager on behalf of the bean. In the latter case, the Container uses information that is supplied by the Deployer. Normally, the value is Container.
<res-sharing-scope>
Specifies whether connections obtained through the given resource manager connection factory reference can be shared. Normally, the value is Shareable.
<message-destination-ref>
Specifies a reference to a message destination associated with a resource in the module's environment. Contains the elements <message-destination-ref-name>, <message-destination-type>, <message-destination-usage>, and <message-destination-link>. It is recommended that the <message-destination-ref> and <message-destination> elements be used instead of the <resource-env-ref> element that was introduced at release 1.3 of the J2EE platform.
<message-destination-ref-name>
Specifies the coded name of a message destination reference. The name is a JNDI name relative to the java:comp/env context, such as jms/NewHireTopic.
<message-destination-type>
Specifies the type of the destination. The type is specified by the Java interface expected to be implemented by the destination. For JMS destinations, the allowed interfaces are javax.jms.Topic and javax.jms.Queue.
<message-destination-usage>
Specifies the use of the message destination indicated by the reference. Must be one of the following: Consumes, Produces, or ConsumesProduces.
<message-destination-link>
Links a message destination reference or message-driven bean to a message destination. For example, if the <message-destination> element has the <message-destination-name> value PhysicalTopic, specify PhysicalTopic as the value of the <message-destination-link> element.
<message-destination>
Specifies a message destination. The logical destination described by this element is mapped to a physical destination by the Deployer. Contains a <message-destination-name> element. In the J2EE Application Server, the name you specify here is the name of the destination you created with the asadmin create-jmsdest command.
<message-destination-name>
Specifies a name for a message destination.

Deployment Descriptor Elements for Message-Driven Beans

The deployment descriptor for a message-driven bean is similar to the deployment descriptor for a session or entity bean in many respects. It includes the messaging-specific elements listed in Table 20-5. The XML Schema files used by the J2EE Application Server are in the directory <J2EE_HOME>/lib/schemas/.

Table 20-5 Deployment Descriptor Elements for Message-Driven Beans
Element Name
Description
<message-driven>
Declares a message-driven bean within an <enterprise-beans> element.
<messaging-type>
Specifies the message listener interface of the message-driven bean. If the <messaging-type> element is not specified, it is assumed to be javax.jms.MessageListener.
<message-destination-type>
Specifies the type of the destination. The type is specified by the Java interface expected to be implemented by the destination, such as javax.jms.Topic.
<message-destination-link>
Links a message destination reference or message-driven bean to a message destination.
<activation-config>
Defines information about the expected configuration properties of the message-driven bean in its operational environment. This may include information about message acknowledgement, message selector, expected destination type, and so on. For details, see Specifying Activation Configuration Properties for Message-Driven Beans. Contains a set of <activation-config-property> elements.
<activation-config-property>
Contains an <activation-config-property-name> and <activation-config-property-value> pair for a message-driven bean.
<activation-config-property-name>
Contains the name for an activation configuration property of a message-driven bean.
<activation-config-property-value>
Contains the value for an activation configuration property of a message-driven bean.

Deployment Descriptor Elements Specified at Runtime

The runtime deployment descriptors for an application specify the runtime linkages between the connection factories and destinations specified in source code and the actual resources in the JNDI namespace. Runtime deployment descriptors vary from one application server to another. This section describes the elements used in the J2EE Application Server runtime deployment descriptors, which are named sun-application.xml, sun-application-client.xml, sun-ejb-jar.xml, and so on. The Document Type Definitions (DTDs) for these deployment descriptors are in the directory <J2EE_HOME>/lib/dtds/.

Table 20-6 lists these elements.

Table 20-6 Runtime Deployment Descriptor Elements
Element Name
Description
<mdb-resource-adapter>
Specifies the module ID of the resource adapter that is responsible for delivering messages to the message-driven bean, as well as the runtime configuration information for the bean. Contains the required element <resource-adapter-mid> and, optionally, an <activation-config> element.
<resource-adapter-mid>
Specifies the module ID of the resource adapter. If you are using the resource adapter that is part of the J2EE Application Server, this value is jmsra.
<resource-ref>
Specifies the runtime bindings of a resource reference. Contains the elements <res-ref-name> and <jndi-name> and, optionally, <default-resource-principal>.
<res-ref-name>
Specifies the coded name of a JMS connection factory, such as jms/MyConnectionFactory.
<default-resource-principal>
Specifies the username and password to be used to access the connection factory, using the <name> and <password> elements.
<message-destination>
Specifies the name and JNDI name of a logical message destination. Contains the elements <message-destination-name> and <jndi-name>.
<message-destination-name>
Specifies the name of a logical message destination. This logical name, which was also specified by the module deployment descriptor (see Table 20-4), is now linked to the JNDI name of the destination.
<jndi-name>
The JNDI name of a JMS resource, which may be either a connection factory or a destination. This is the name you specified when you created the resource administratively.

Specifying Activation Configuration Properties for Message-Driven Beans

Activation configuration properties are needed to configure message-driven beans at release 1.4 of the J2EE platform if the JMS API is integrated using a J2EE Connector Architecture resource adapter. This section describes the properties you may specify for message-driven beans that consume JMS messages.

You may specify these properties either in the enterprise bean deployment descriptor or in the runtime deployment descriptor, or both. Any properties specified in the runtime deployment descriptor override the properties specified in the enterprise bean deployment descriptor.

Table 20-7 lists these properties.

Table 20-7 Activation Configuration Property Names and Values
Property Name
Description and Values
destinationType
(Required) The interface type of the destination, either javax.jms.Topic or javax.jms.Queue.
destination
(Required) The name of the destination in the JNDI namespace, such as jms/Topic.
messageSelector
A message selector.
subscriptionDurability
A value of Durable indicates that the message-driven bean is a durable subscriber to a topic. If the value is Durable, then the clientId and subscriptionName properties must also be specified.
A value of NonDurable specifies that the bean is not using a durable subscription. If omitted, the bean is assumed to be a nondurable subscriber if the destinationType value is javax.jms.Topic.
clientId
The client ID of the connection factory used by the message-driven bean, if it is using a durable subscription.
subscriptionName
The name of the subscription, which identifies the subscription uniquely in conjunction with the topic name and the clientId value, if the bean is using a durable subscription.
acknowledgeMode
The acknowledgment mode of the bean, either Auto-acknowledge or Dups-ok-acknowledge. If not specified, assumed to be Auto-acknowledge.
addressList
The URL of a remote connection factory, using the format system-name[:port-number], as described in Running JMS Client Programs on Multiple Systems. Used for a message-driven bean that consumes messages from a remote destination.

Divider
Download
FAQ
History
HomeHomeNext API
Search
Feedback
Divider

All of the material in The J2EE 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.